package com.atguigu.srb.base.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;

@Configuration
@EnableCaching//启用缓存管理
public class RedisConfig {
    //给RedisTemplate配置键值序列化器
    @Resource
    RedisTemplate redisTemplate;


    //在当前配置类对象初始化后立即给装配的成员属性redisTemplate设置键值序列化器
    @PostConstruct //java提供的注解：标注的成员方法可以在当前类构造器调用后立即执行一次
    public void init(){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
    }

    //springboot引入了springdataredis启动器，启动时如果引入了commons-pool2依赖，会初始化LettuceConnectionFactory
    //注入到容器中。
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory factory){

        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(600)) //缓存过期时间
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer())) //建序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()));//值序列化器
                //缓存空值：可以解决缓存穿透问题(每次查询数据库一定不存在的数据时，请求先走redis，再查数据库)
                //布隆过滤器
                //.disableCachingNullValues();
        return RedisCacheManager.builder(factory)
                .cacheDefaults(configuration)
                .build();
    }



}
